package com.csvw.skr.console.resource;

import com.csvw.skr.basic.entity.Organization;
import com.csvw.skr.basic.entity.User;
import com.csvw.skr.basic.service.ResourceService;
import com.csvw.skr.console.service.OrganizationService;
import com.csvw.skr.console.service.UserService;
import com.google.common.collect.Lists;

import com.webonn.frame.core.OAuthPrincipal;
import com.webonn.frame.core.Pagination;
import com.webonn.frame.util.APIResultBuilder;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@PermitAll
@CrossOrigin
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF-8", MediaType.TEXT_HTML + "; charset=UTF-8"})
@RestController
@RequestMapping("/resource")
public class ResourceResource {

    @Autowired
    private UserService userService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private OrganizationService organizationService;

    /**
     * 获取组织树
     * organization只有组织
     *
     * @param pid 父节点id
     */
    @RequestMapping(value="/organization/tree/{pid}", method= RequestMethod.GET)
    public Response queryOrganizationTree(OAuthPrincipal principal, @PathVariable String pid) {
        User current = userService.getUser(principal.getName());
        Organization organization = organizationService.getOrganization(current.getOrganization());
        int level = organization.getLevel();

        List<Map<String, Object>> result;

        //检查pid是否为空
        if (pid != null && !"0".equals(pid)) {
            result = resourceService.queryOrganizationTree(pid, level, false);
        } else {
            result = resourceService.queryOrganizationTree(organization.getCode(), level, true);
        }

        if (result != null) {
            return APIResultBuilder.OK(result);
        } else {
            return APIResultBuilder.NOT_FOUND("未查询到数据");
        }
    }

    /**
     * 获取组织树 点检统计中 该点检的组织树
     * organization只有组织
     *
     * @param pid 父节点id
     */
    @RequestMapping(value="/organization/tree/{pid}/inspectionDraft/{inspectionDraftId}", method= RequestMethod.GET)
    public Response queryInspectionDraftOrganizationTree(OAuthPrincipal principal, @PathVariable String pid,
                                                         @PathVariable String inspectionDraftId) {
        User current = userService.getUser(principal.getName());
        Organization organization = organizationService.getOrganization(current.getOrganization());
        int level = organization.getLevel();

        List<Map<String, Object>> result;

        //检查pid是否为空
        if (pid != null && !"0".equals(pid)) {
            result = resourceService.queryInspectionDraftOrganizationTree(pid, level, false, inspectionDraftId);
        } else {
            result = resourceService.queryInspectionDraftOrganizationTree(organization.getCode(), level, true, inspectionDraftId);
        }

        if (result != null) {
            return APIResultBuilder.OK(result);
        } else {
            return APIResultBuilder.NOT_FOUND("未查询到数据");
        }
    }

    /**
     * 获取组织树
     * dealer带经销商的组织树
     *
     * @param pid 父节点id
     * @return
     */
    @RequestMapping(value="/dealer/tree/{pid}", method= RequestMethod.GET)
    public Response queryDealerTree(OAuthPrincipal principal, @PathVariable String pid) {
        User current = userService.getUser(principal.getName());
        Organization organization = organizationService.getOrganization(current.getOrganization());
        int level = organization.getLevel();

        List<Map<String, Object>> result;

        //检查pid是否为空
        if (pid != null && !"0".equals(pid)) {
            result = resourceService.queryDealerTree(pid, level, false);
        } else {
            result = resourceService.queryDealerTree(organization.getCode(), level, true);
        }

        if (result != null) {
            return APIResultBuilder.OK(result);
        } else {
            return APIResultBuilder.NOT_FOUND("未查询到数据");
        }
    }

    /**
     * @param dealersOrOrganization 包含 List<String>  和 dealers 的map
     */
    @RequestMapping(value="/organization/dealer/info", method= RequestMethod.POST)
    public Response getDealerInfo(Map<String, Object> dealersOrOrganization) {
        if (dealersOrOrganization == null) return APIResultBuilder.OK(Lists.newArrayList());

        List<String> organizations = (List<String>) dealersOrOrganization.getOrDefault("organizations", Lists.newArrayList());
        String dealers = (String) dealersOrOrganization.getOrDefault("dealers", "");

        //TODO 权限判断 不是该用户的下属经销商不能添加
        return APIResultBuilder.OK(resourceService.getDealerInfoByDealerIdOrOrgId(organizations, dealers));
    }

    /**
     * 根据level获取organization的selection
     */
    @RequestMapping(value="/organization/level/selection/{level}/{pcode}", method= RequestMethod.GET)
    public Response queryOrganizationSelection(@DefaultValue("1") @QueryParam("page") int page,
                                               @DefaultValue("20") @QueryParam("length") int limit,
                                               @DefaultValue("") @QueryParam("search") String search,
                                               @PathVariable int level, @PathVariable String pcode) {
        Pagination result = resourceService.queryOrganizationLevelSelection((page - 1) * limit, limit, search, level, pcode);
        return APIResultBuilder.OK(result);
    }

    /**
     * 根据pid获取省市县的selection
     */
    @RequestMapping(value="/dic/selection/{pid}", method= RequestMethod.GET)
    public Response queryDicRegionSelection(@DefaultValue("1") @QueryParam("page") int page,
                                            @DefaultValue("20") @QueryParam("length") int limit,
                                            @DefaultValue("") @QueryParam("search") String search,
                                            @PathVariable String pid) {
        int parentId = 9999;
        try {
            parentId = Integer.valueOf(pid);
        } catch (NumberFormatException e) {
            parentId = resourceService.queryDicPidByName(pid);
        }
        Pagination result = resourceService.queryDicRegionSelection((page - 1) * limit, limit, search, parentId);
        return APIResultBuilder.OK(result);
    }

    /**
     * 根据level获取菜单selection
     */
    @RequestMapping(value="menu/selection/{level}", method= RequestMethod.GET)
    public Response queryMenuSelection(@DefaultValue("1") @QueryParam("page") int page,
                                       @DefaultValue("20") @QueryParam("length") int limit,
                                       @DefaultValue("") @QueryParam("search") String search,
                                       @PathVariable int level) {
        Pagination result = resourceService.queryMenuLevelSelection((page - 1) * limit, limit, search, level);
        return APIResultBuilder.OK(result);
    }

    /**
     * 获取用户pc端相应父菜单的子菜单
     */
    @RequestMapping(value="/user/menu/{pcode}", method= RequestMethod.GET)
    public Response getPcMenuByPcode(HttpServletRequest request, @PathVariable String pcode,
                                     @QueryParam("maxLevel") int maxLevel) {
        String userId = (String) request.getAttribute("userId");
        return APIResultBuilder.OK(resourceService.queryUserMenuByPcode(userId, pcode, maxLevel, false, false));
    }

    /**
     * 获取用户app端相应父菜单的子菜单
     */
    @RequestMapping(value="/user/menu/app/{pcode}", method= RequestMethod.GET)
    public Response getAppMenuByPcode(OAuthPrincipal principal, @PathVariable String pcode,
                                      @QueryParam("maxLevel") int maxLevel) {
        return APIResultBuilder.OK(resourceService.queryUserMenuByPcode(principal.getName(), pcode, maxLevel, true, false));
    }


    /**
     * app 快捷跳转接口
     */
    @RequestMapping(value="/user/app/report/menu", method= RequestMethod.GET)
    public Response getUserAppReportMenu(OAuthPrincipal principal, @QueryParam("maxLevel") int maxLevel) {
        return APIResultBuilder.OK(resourceService.queryUserMenuByPcode(principal.getName(), "skr_report_app", 3, true, true));
    }

    /**
     * 当前用户的经销商 selection
     */
    @RequestMapping(value="/user/dealer/selection", method= RequestMethod.GET)
    public Response queryUserDealerSelection(OAuthPrincipal principal,
                                             @DefaultValue("1") @QueryParam("page") int page,
                                             @DefaultValue("20") @QueryParam("length") int limit,
                                             @DefaultValue("") @QueryParam("search") String search) {
        Pagination result = resourceService.queryUserDealerSelection((page - 1) * limit, limit, search, principal.getName());
        return APIResultBuilder.OK(result);
    }

    /**
     * 用户selection
     */
    @RequestMapping(value="/user/selection/{type}/{value}", method= RequestMethod.GET)
    public Response queryUserSelection(OAuthPrincipal principal,
                                       @DefaultValue("1") @QueryParam("page") int page,
                                       @DefaultValue("20") @QueryParam("length") int limit,
                                       @DefaultValue("") @QueryParam("search") String search,
                                       @PathVariable String type, @PathVariable String value) {

        Pagination result = resourceService.queryUserSelection((page - 1) * limit, limit, search, type, value);

        if (Objects.nonNull(result)) {
            return APIResultBuilder.OK(result);
        } else {
            return APIResultBuilder.UnprocesableEntity("参数错误");
        }
    }

    @RequestMapping(value="/model/tree", method= RequestMethod.GET)
    public Response listModelTree() {
        return APIResultBuilder.OK(resourceService.listModelTree());
    }
}
